package cn.cvs.controller;

import cn.cvs.entity.Supplier;
import cn.cvs.service.SysSupplierService;
import cn.cvs.utils.PageSupport;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/supplier")
public class SupplierController {
    Logger logger = Logger.getLogger(SupplierController.class);
    @Autowired
    private SysSupplierService supplierService;

    //捕获异常信息，跳转到error页面
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest req) {
        req.setAttribute("e", e);
        return "sysError";
    }
    //跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError() {
        return "sysError";
    }

//    @GetMapping(
//            value = {"/simpleList"},
//            produces = {"application/json;charset=UTF-8"}
//    )
//    @ResponseBody
//    public List<Supplier> getSupplierList() {
//        List simpleList = null;
//
//        try {
//            simpleList = this.supplierService.selectList();
//        } catch (Exception var3) {
//            var3.printStackTrace();
//        }
//
//        return simpleList;
//    }

    @RequestMapping({"/list"})
    public String getSupplierList(Model model, HttpSession session, @RequestParam(value = "querySupCode",required = false) String querySupCode, @RequestParam(value = "querySupName",required = false) String querySupName, @RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex) throws Exception {
        List<Supplier> supplierList = null;
        int pageSize = 5;
        int totalCount = this.supplierService.selectCount(querySupCode, querySupName);
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(pageIndex);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        if (pageIndex > totalPageCount) {
            pageIndex = totalPageCount;
        }

        supplierList =supplierService.selectList(querySupName, querySupCode, pageIndex, pageSize);
        model.addAttribute("supplierListt", supplierList);


        model.addAttribute("querySupCode", querySupCode);
        model.addAttribute("querySupName", querySupName);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", pageIndex);
        return "supplier/list";
    }

}
